package team.kirohuji.controller;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import team.kirohuji.domain.user.User;
import team.kirohuji.repository.jpa.user.UserRepository;
import team.kirohuji.service.user.UserService;
import team.kirohuji.utils.JWTUtil;
import team.kirohuji.utils.R;
import team.kirohuji.utils.ShiroUtils;

/**
 * 
 * 这个Controller用来管理用户的登录和查看用户的登录信息
 * @author kirohuji
 * @version 0.1
 */
@Controller
public class LoginController{
	 private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
	/**
	 * @see UserService
	 */
	@Resource
	private UserService userService;
	
	@Autowired
	private UserRepository userRepository;
	
	/**
	 * 登录
	 * 
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @param session
	 *            会话Session
	 * @return {@link team.kirohuji.utils.R}
	 * @throws IOException
	 *             可能会抛出了一个IO异常
	 */
	@ResponseBody
	@RequestMapping(value = "/sign/in", method = RequestMethod.POST)
	public ResponseBean login(String username, String password) throws IOException {
		try {
			Subject subject = ShiroUtils.getSubject();
			//1. 执行登录
            //把用户名和密码封装为UsernamePasswordToken对象
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			System.out.println(username+"::"+password);
			subject.login(token);
	        if (subject.isAuthenticated()) {
	        	User user = userService.queryByLoginName(username);
	        	System.out.println(user.getPassword());
	            return new ResponseBean(200, "Login success", JWTUtil.sign(username, user.getPassword()));
	        } else {
	            return new ResponseBean(200, "You are guest", null);
	        }
		} catch (UnknownAccountException e) {
			return new ResponseBean(401, e.getMessage(), null);
		} catch (IncorrectCredentialsException e) {
			return new ResponseBean(401, e.getMessage(), null);
		} catch (LockedAccountException e) {
			return new ResponseBean(401, e.getMessage(), null);
		} catch (ExcessiveAttemptsException e) {
			return new ResponseBean(401, e.getMessage(), null);
		} catch (AuthenticationException e) {
			System.out.println(e.getMessage());
			return new ResponseBean(401, "账户验证失败", null);
		}
	}

	/**
	 * 退出
	 * 
	 * @param session
	 *            Http会话
	 * @return String 进行地址跳转
	 */
	@RequestMapping(value = "/sign/out", method = RequestMethod.GET)
	public String logout() {
		ShiroUtils.logout();
		return "redirect:login.html";
	}

	/**
	 * 获取登录的用户信息
	 * 
	 * @param session
	 *            会话
	 * @return {@link team.kirohuji.utils.R}
	 */
	@RequestMapping("/info")
	@ResponseBody
	public R info(HttpSession session) {
		User user = (User) session.getAttribute("user");
		return R.ok().put("user", user);
	}

	/**
	 * 注册的路由映射
	 * 
	 * @return String 地址
	 */
	@RequestMapping(value = "/sign/up", method = RequestMethod.GET)
	public String register() {
		return "page/register";
	}
	
	/**
	 * 进行 路由 设置
	 * @param url
	 * @return
	 */
	@RequestMapping("{suffix}/{url}.html")
	public String router(@PathVariable("suffix") String suffix,@PathVariable("url") String url){
		return suffix+"/" + url;
	}
	
}
